package cat.music.ut.comm.viewutils

import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import cat.music.ut.CatApp
import cat.music.ut.component.dp2px


class SoftKeyBroadManager(
    private val rootView: View,
    private val targetView: View,
    private val offset: Int = 50
) {
    private var isShow = false

    init {
        // 监听布局变化
        rootView.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            rootView.getWindowVisibleDisplayFrame(rect)

            val screenHeight = rootView.rootView.height
            val keyboardHeight = screenHeight - rect.bottom

            if (keyboardHeight > screenHeight * 0.15) { // 键盘高度超过屏幕15%时，认为键盘已显示
                if (isShow) return@addOnGlobalLayoutListener
                if (keyboardHeight != previousKeyboardHeight) {
                    // 键盘高度变化，调整输入框位置
                    adjustInputFieldPosition(keyboardHeight)
                    previousKeyboardHeight = keyboardHeight
                }
                isShow = true
            } else {
                if (!isShow) return@addOnGlobalLayoutListener
                // 键盘隐藏，恢复输入框位置
                resetInputFieldPosition()
                previousKeyboardHeight = 0
                isShow = false
            }
        }
    }

    /**
     * 调整输入框位置
     */
    private fun adjustInputFieldPosition(keyboardHeight: Int) {
        val params = targetView.layoutParams as ViewGroup.MarginLayoutParams
        params.bottomMargin = keyboardHeight // 将输入框的底部边距设置为键盘高度
        targetView.layoutParams = params
        callback.invoke(true)
    }

    /**
     * 恢复输入框位置
     */
    private fun resetInputFieldPosition() {
        val params = targetView.layoutParams as ViewGroup.MarginLayoutParams
        params.bottomMargin = dp2px(CatApp.getInstance(), offset) // 恢复输入框的底部边距
        targetView.layoutParams = params
        callback.invoke(false)
    }

    private var previousKeyboardHeight = 0
    private var callback: (Boolean) -> Unit = {} // true 说明顶上去了，false 则回复原来
    fun setCallback(callback: (Boolean) -> Unit) {
        this.callback = callback
    }

    fun build(): SoftKeyBroadManager {
        return this
    }

}

/**
 * 隐藏软键盘(可用于Activity，Fragment)
 */
fun hideSoftKeyboard(context: Context, viewList: List<View>?) {
    if (viewList == null) return

    val inputMethodManager =
        context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager

    for (v in viewList) {
        inputMethodManager.hideSoftInputFromWindow(
            v.windowToken,
            InputMethodManager.HIDE_NOT_ALWAYS
        )
    }
}